package 重温_Java并发基础.CompletableFuture案例.商店信息查询模型;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author idea
 * @data 2020/2/21
 */
public class MutiShop {

    List<Shop> shops = Arrays.asList(
            new Shop("best price1"),
            new Shop("best price2"),
            new Shop("best price3"),
            new Shop("best price4"),
            new Shop("best price5"),
            new Shop("best price6")
    );


    /**
     * stream 6261ms
     * parallelStream  2230ms
     * CompletableFuture 2228ms
     */
    public List<String> findAllPrice(String product) {
//        List<String> result = new ArrayList<>();
//        for (Shop shop : shops) {
//            double p = shop.getPrice();
//            result.add(shop.getName() + p);
//        }
//        return result;

//        return shops.parallelStream()
//                .map(shop -> String.format("%s's price is %.2f",
//                        shop.getName(), shop.getPrice())).collect(Collectors.toList());
        List<CompletableFuture<String>> priceFutures = shops
                .stream().map(shop ->
                        CompletableFuture.supplyAsync(() -> String.format("%s's price is %.2f"
                                , shop.getName()
                                , shop.getPrice()))
                ).collect(toList());
        return priceFutures.parallelStream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
    }


    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        MutiShop mutiShop = new MutiShop();
        List<String> result = mutiShop.findAllPrice("product");
        System.out.println(result);
        long end = System.currentTimeMillis();
        System.out.println(end - begin);
    }
}
